package net.TCPTwoWayChat;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TwoWayServer {

    public static void main(String[] args) throws IOException {

        ServerSocket serverPlatform = new ServerSocket(8888);
        System.out.println("服务平台创建成功");

        Socket serverSocket = serverPlatform.accept();
        System.out.println("已经有客户端与服务端连接成功");


        //创建一个从客户端的一个输入流
        BufferedReader fromClientStream = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
        //创建一个向客户端写出的输出流
        PrintWriter toClientStream = new PrintWriter(new OutputStreamWriter(serverSocket.getOutputStream()));


        //使用匿名内部类的形式创建一个从服务端向客户端写数据的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                Scanner scan = new Scanner(System.in);
                while(true){
                    String message = scan.nextLine();
                    toClientStream.println(message);
                    toClientStream.flush();
                }
            }
        }).start();

        //使用匿名内部类的形式创建一个从客户端读数据的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String line;
                    while((line=fromClientStream.readLine())!=null){
                        System.out.println("客户端说:"+line);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
